import os

from django.http import HttpResponseRedirect
from django.db import transaction
from op_drf.filters import DataLevelPermissionsFilter
from .handler import *
from django.shortcuts import render
from loguru import logger
from rest_framework.request import Request
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters, status
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element
from datetime import datetime
import requests

from apps.prescription.filters import PrescriptionFilter, DrugFilter
from op_drf.pagination import Pagination
from op_drf.response import SuccessResponse, ErrorResponse

from op_drf.dj_utils import set_delete, create_by_serializer
from op_drf.viewsets import CustomModelViewSet
from apps.prescription.models import Prescription, Drug
from apps.prescription.serializers import WritePrescriptionSerializer, ReadPrescriptionSerializer, WriteDrugSerializer, \
    ReadDrugSerializer
from op_drf.viewsets import ModelViewSet
from ..Order.models import Order
from ..TabletInfo.models import TabletInfo
from ..staruser.models import LoginHistory, StarUser


# Create your views here.

class PrescriptionView(CustomModelViewSet):
    """
    处方信息的CRUD
    """
    queryset = Prescription.objects.filter(is_delete=False)
    serializer_class = ReadPrescriptionSerializer  # 序列化器
    # 分页
    pagination_class = Pagination
    # 筛选
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = PrescriptionFilter
    search_fields = ("id", )
    filter_fields = ("id", )
    ordering_fields = ("-id",)
    ordering = ["-create_datetime"]

    def create(self, request: Request, *args, **kwargs):
        MedItem = request.data.pop("MedItem", None)
        assert MedItem,f"参数错误，未传入药品信息"
        logger.debug(MedItem)

        logger.debug(request.data)
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        logger.debug(serializer.data)
        headers = self.get_success_headers(serializer.data)
        id = serializer.data.get("id","0")

        # 批量添加药品及服药方式
        drug_data = []
        for medit in MedItem:
            medna = medit.get("MedNa",None)
            meditemdose = medit.get("MedItemDose",None)
            assert meditemdose,f"{medna}缺少服药方式"

            doselist = meditemdose.get("DoseList",None)
            takedays = meditemdose.get("TakeDays",None)
            drtscd = meditemdose.get("drtscd",None)

            drug_data.append({"MedNa":medna,
                                "MedNote":medit.get("MedNote",None),
                                "doselist":doselist,
                                "takedays":takedays,
                                "drtscd":drtscd,
                                "prescrption":id})

        # 批量添加药品
        drug_serializer = create_by_serializer(
            WriteDrugSerializer, data=drug_data, context=self.get_serializer_context(),many=True
        )
        return SuccessResponse(serializer.data, headers=headers)

    def update(self, request: Request, *args, **kwargs):
        logger.debug("前端传入的数据： %s" % request.data)
        logger.debug("请求携带的数据： %s" % kwargs)
        instance = self.get_object()
        msg = ""
        if not instance:
            msg = "请确定要修改的药方"
            return ErrorResponse(msg=msg)
        is_active = request.data.get("is_active", None)
<<<<<<< HEAD

        if instance:
            if str(instance.is_active) == is_active:
                return ErrorResponse(msg="不允许重复修改药方状态")
            else:
                instance.is_active = is_active
                instance.save()
                if is_active:
                    logger.debug(is_active)
                    logger.debug(type(is_active))
                    msg = "已确定使用该药方"
                else:
                    msg = "已取消使用该药方"
=======
        if not is_active:
            return ErrorResponse(msg="未设置药单状态")
        if instance and is_active:
            if str(instance.is_active) == is_active:
                return ErrorResponse(msg="不允许重复修改药方状态")
            else:
                instance.is_active = True if is_active == "1" else False
                instance.save()
                logger.debug(type(is_active))
                if is_active=="1":
                    msg = f"已确定使用该药方"
                    logger.debug(msg)
                else:
                    msg = f"已取消使用该药方"
                    logger.debug(msg)
>>>>>>> dev

        return SuccessResponse(msg=msg)

    # 根据数据生成xml文件
    def Create_YF(self, request: Request, *args, **kwargs):
        logger.debug("前端传入的数据： %s" % request.data)
        logger.debug("请求携带的数据： %s" % kwargs)

        # 订单id
        id = request.data.get("id",0)
        if not id:
            return ErrorResponse(msg=f"参数错误")

        orders = Order.objects.exclude(OrderStatus=1).filter(is_delete=False,pk=id)
        if not orders:
            pass
        else:
            order_obj = orders[0]
            prescrption = order_obj.prescription
            if prescrption:
                prescrption_obj = prescrption
            else:
                return ErrorResponse(msg="未找到处方，请检查！")
            if not prescrption_obj.is_active:
                return ErrorResponse(msg=f"处方状态错误，请检查！")
            # 采用名称命名的文件
            file_name = prescrption_obj.PtntNm+datetime.now().strftime("%Y%m%d%H")+".xml"

            # 创建根目录
            root = ET.Element('OrderInfo')
            tree = ET.ElementTree(root)

            # 处方编号(唯一)
            ordernum = Element('OrderNum')
            ordernum.text = prescrption_obj.OrderNum if prescrption_obj.OrderNum else ""
            root.append(ordernum)
            # 药方发药日期
            orderdt = Element('OrderDt')
            orderdt.text = prescrption_obj.OrderDt.strftime("%Y%m%d") if prescrption_obj.OrderDt else ""
            root.append(orderdt)

            # 药方发药具体时间
            orderdtm = Element('OrderDtm')
            orderdtm.text = prescrption_obj.OrderDtm.strftime("%Y%m%d%H%M%S") if prescrption_obj.OrderDtm else ""
            root.append(orderdtm)
            # 病人ID号(唯一)，通过病人信息获取
            ptntnum = Element('PtntNum')
            ptntnum.text = '0000381877' #prescrption_obj.PtntNm if prescrption_obj.PtntNm else ""
            root.append(ptntnum)

            # 科室代码
            dptmptcd = Element('DptmtCd')
            dptmptcd.text = '1015'
            root.append(dptmptcd)
            # 性别
            sex = Element('Sex')
            sex.text = 'F'
            root.append(sex)

            # 生日 通过病人信息获取
            birthday = Element('Birthday')
            birthday.text = datetime.now().strftime("%Y%m%d")
            root.append(birthday)
            # 病人居住地址
            ptntaddr = Element('PtntAddr')
            ptntaddr.text = ' '
            root.append(ptntaddr)

            # 病人电话号码
            ptnttel = Element('PtntTel')
            ptnttel.text = ' '
            root.append(ptnttel)

            # 住院I临时O
            inoutclsf = Element('InOutClsf')
            inoutclsf.text = 'I'
            root.append(inoutclsf)

            # 医院代码
            hsptcd = Element('HsptCd')
            # hsptcd.text = website_obj.HsptCd if website_obj.HsptCd else ""
            hsptcd.text = "医院编码"
            root.append(hsptcd)
            # 医生姓名
            # 从医生中筛选
            # doctor = Doctor.objects.filter(is_delete=False,is_active=True,pk=1)
            # if doctor:
            #     doctor_obj = doctor[0]
            #     doctornm = Element('DoctorNm')
            #     doctornm.text = doctor_obj.name if doctor_obj.name else ""
            #     root.append(doctornm)

            doctornm = Element('DoctorNm')
            doctornm.text = "医生"
            root.append(doctornm)

            # 病人姓名
            ptntnm = Element('PtntNm')
            ptntnm.text = prescrption_obj.PtntNm if prescrption_obj.PtntNm else ""
            root.append(ptntnm)

            # 病区代码
            wardcd = Element('WardCd')
            wardcd.text = '1015'
            root.append(wardcd)
            # 病房号
            roomnum = Element('RoomNum')
            roomnum.text = 'O11'
            root.append(roomnum)

            # 病床号
            bednum = Element('BedNum')
            bednum.text = 'O11'
            root.append(bednum)

            # 处方文件分类
            dataclsf = Element('DataClsf')
            dataclsf.text = 'N'
            root.append(dataclsf)

            # 药品信息(循环获取)
            drugs = prescrption_obj.drug_set.filter(is_delete=False)

            for drug in drugs:

                if drug.tablet:
                    # 自编药方直接提取
                    meditem = Element('MedItem')
                    # 药品编码,需通过药品名称查找
                    medcd = Element('MedCd')
                    logger.debug(drug)
                    medcd.text = drug.MedCd if drug.MedCd else ""
                    logger.debug(1)
                    meditem.append(medcd)

                    # 药品名称
                    mednm = Element('MedNm')
                    mednm.text = drug.MedNm if drug.MedNm else ""
                    meditem.append(mednm)

                    # 二维码
                    mednote = Element('MedNote')
                    mednote.text = '1234'
                    meditem.append(mednote)

                    # 药品单位
                    medunit = Element('MedUnit')
                    medunit.text = drug.MedUnit if drug.MedUnit else ""
                    meditem.append(medunit)

                    # 药品规格
                    medspec = Element('MedSpec')
                    medspec.text = drug.MedSpec if drug.MedSpec else ""
                    meditem.append(medspec)

                    # 是否使用包药机
                    useatcyn = Element('UseAtcYn')
                    useatcyn.text = "Y"
                    meditem.append(useatcyn)

                    meditemdose = Element('MedItemDose')

                    takedays = Element('TakeDays')
                    takedays.text = str(int(drug.takedays)) if drug.takedays else ""
                    meditemdose.append(takedays)

                    doselist = Element('DoseList')
                    doselist.text = drug.doselist if drug.doselist else ""
                    meditemdose.append(doselist)

                    dosenote = Element('DoseNote')
                    dosenote.text = drug.MedNote if drug.MedNote else ""
                    meditemdose.append(dosenote)

                    drtscd = Element('DrtsCd')
                    drtscd.text = drug.drtscd if drug.drtscd else ""
                    meditemdose.append(drtscd)
                    meditem.append(meditemdose)
                    root.append(meditem)
                else:
                    # 从云医传递过来的需要到药品库中查找
                    tabletinfo = TabletInfo.objects.filter(tblt_nm=drug.MedNm).order_by("-id")

                    if tabletinfo:
                        tablet_obj = tabletinfo[0]

                    meditem = Element('MedItem')
                    # 药品编码,需通过药品名称查找
                    medcd = Element('MedCd')
                    medcd.text = tablet_obj.tblt_cd if tablet_obj.tblt_cd else ""
                    meditem.append(medcd)

                    # 药品名称
                    mednm = Element('MedNm')
                    mednm.text = tablet_obj.tblt_nm if tablet_obj.tblt_nm else drug.MedNa
                    meditem.append(mednm)

                    # 二维码
                    mednote = Element('MedNote')
                    mednote.text = '1234'
                    meditem.append(mednote)

                    # 药品单位
                    medunit = Element('MedUnit')
                    medunit.text = tablet_obj.tblt_unit if tablet_obj.tblt_unit else drug.MedNa
                    meditem.append(medunit)

                    # 药品规格
                    medspec = Element('MedSpec')
                    medspec.text = tablet_obj.tblt_spec if tablet_obj.tblt_spec else drug.MedNm
                    meditem.append(medspec)

                    # 是否使用包药机
                    useatcyn = Element('UseAtcYn')
                    useatcyn.text = "Y"
                    meditem.append(useatcyn)

                    meditemdose = Element('MedItemDose')

                    takedays = Element('TakeDays')
                    takedays.text = str(int(drug.takedays)) if drug.takedays else ""
                    meditemdose.append(takedays)


                    doselist = Element('DoseList')
                    doselist.text = drug.doselist if drug.doselist else ""
                    meditemdose.append(doselist)

                    dosenote = Element('DoseNote')
                    dosenote.text = drug.MedNote if drug.MedNote else ""
                    meditemdose.append(dosenote)

                    drtscd = Element('DrtsCd')
                    drtscd.text = drug.drtscd if drug.drtscd else ""
                    meditemdose.append(drtscd)
                    meditem.append(meditemdose)
                    root.append(meditem)
            # 写入文件并添加头文件说明
            floder_path = os.path.join("Rad","florder")
            if not os.path.exists(floder_path):
                os.makedirs(floder_path,exist_ok=True)

            localfile = os.path.join(floder_path, file_name)
            with open(localfile, 'wb') as fs:
                tree.write(fs, encoding='utf-8', xml_declaration=True)

            # 加事务
            with transaction.atomic():
                uploadfile(order_obj.rad.pk,file_name,localfile)
                order_obj.OrderStatus="1"
                order_obj.save()
                prescrption.OrderStatus="1"
                prescrption.save()

            return SuccessResponse(msg="已生成Rad药方")


class DrugView(CustomModelViewSet):
    """
    处方信息的CRUD
    """
    queryset = Drug.objects.filter(is_delete=False)
    serializer_class = ReadDrugSerializer  # 序列化器
    create_serializer_class = WriteDrugSerializer
    update_serializer_class = WriteDrugSerializer
    # 分页
    pagination_class = Pagination
    # 筛选
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = DrugFilter
    search_fields = ("id", )
    filter_fields = ("id", )
    ordering_fields = ("-id",)
    ordering = ["-create_datetime"]

    def create(self, request: Request, *args, **kwargs):
        logger.debug("前端传入的数据： %s" % request.data)
        logger.debug("请求携带的数据： %s" % kwargs)

        tabletinfo_id = request.data.get("tablet_info",0)
        if tabletinfo_id:
            tabletinfo = TabletInfo.objects.filter(pk=tabletinfo_id)
            if tabletinfo:
                tablet_obj = tabletinfo[0]
                logger.debug(tablet_obj.tblt_nm)
                request.data["MedNm"] = tablet_obj.tblt_nm
                tblt_cd = "cd"
                request.data["MedCd"] = tblt_cd
                request.data["MedUnit"] = "粒"
        prescrption_id = request.data.get("prescrption",0)

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        logger.debug("序列化后的数据： %s" % serializer.data)
        return SuccessResponse(serializer.data, status=status.HTTP_201_CREATED, headers=headers)


def selfcreate(request):
    # 当前登录用户
    user_id = request.session.get("userid", None)
    if not user_id:
        return HttpResponseRedirect('/user/login')
    # 新增自编方数据表
    prescription = Prescription.objects.filter(is_delete=False,OrderStatus="0",OrderType="0",user__id=user_id)
    logger.debug(1)
    if prescription:
        logger.debug(1)
        prescription_obj = prescription[0]
    else:
        logger.debug(1)
        staruser_obj = StarUser.objects.filter(pk=user_id)[0]
        prescription_obj = Prescription.objects.create(OrderDt=datetime.now(),
                                                       OrderNum=datetime.now().strftime("%Y%m%d%H%M%S"),
                                                       OrderDtm=datetime.now(),
                                                       OrderType="0",
                                                       user=staruser_obj)
    logger.debug(1)
    tablet_info = TabletInfo.objects.all()
    logger.debug(1)
    context = {"OrderDt":prescription_obj.OrderDt.strftime("%Y-%m-%d"),
               "OrderNum":prescription_obj.OrderNum,
               "prescription_id":prescription_obj.pk,
               "tablet_info_list":tablet_info}
    logger.debug(1)
    return render(request, os.path.join("prescription","self_prescrip.html"), context)


def buy_med(request):
    user_id = request.session.get("userid", None)
    if not user_id:
        return HttpResponseRedirect('/user/login')
    context = {'user_id':user_id}
    return render(request,os.path.join("prescription","userinfo.html"),context)

def zhenliao(request):
    context = {}
    return render(request,'zhenliao.html',context)

def pengsong(request):
    context = {}
    return render(request,'peisong.html',context)